package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.CustomerDTO;
import com.tree.backend.entity.pojo.Customer;
import com.tree.backend.entity.pojo.PowerZone;
import com.tree.backend.entity.vo.CustomerVO;
import com.tree.backend.mapper.CustomerMapper;
import com.tree.backend.mapper.PowerZoneMapper;
import com.tree.backend.mapper.UserMapper;
import com.tree.backend.service.ICustomerService;
import com.tree.backend.utils.DataMappingUtils;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 客户基本信息表 服务实现类
 * </p>
 *
 * @author tree
 * @since 2025-11-09
 */
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    private final PowerZoneMapper powerZoneMapper;

    @Override
    public Result<Page<CustomerVO>> getList(CustomerDTO customerDTO) {
        // 1. 初始化区域名称映射Map
        final Map<Integer, String> powerZoneNameMap = new HashMap<>();
        LambdaQueryWrapper<Customer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        
        // 使用通用权限过滤方法替代原有的Stream转换逻辑
        boolean hasAppliedPermission = DataMappingUtils.applyPermissionFilter(
                // 权限条件：企业ID不为0
                () -> UserContext.getCompanyId() != 0,
                // 获取权限数据：根据企业ID获取权限区域
                () -> powerZoneMapper.selectList(new LambdaQueryWrapper<PowerZone>().eq(PowerZone::getCompanyId, UserContext.getCompanyId())),
                // 提取权限ID：区域ID
                PowerZone::getId,
                // 提取权限名称：区域名称
                PowerZone::getZoneName,
                // 权限映射Map
                powerZoneNameMap,
                // 查询条件构建器
                lambdaQueryWrapper,
                // 实体权限字段：客户的区域ID
                Customer::getPowerZoneId
        );
        
        // 如果未应用权限过滤（即超级管理员或特殊情况），不需要额外处理
        // 因为后面的buildIdNameMap会自动填充所需的区域名称
        
        // 2. 条件查询分页
        // 添加其他查询条件
        lambdaQueryWrapper
                .like(StringUtils.isNotBlank(customerDTO.getCustomerName()), Customer::getCustomerName, customerDTO.getCustomerName())
                .like(StringUtils.isNotBlank(customerDTO.getCustomerCode()), Customer::getCustomerCode, customerDTO.getCustomerCode())
                .eq(customerDTO.getCustomerType() != null, Customer::getCustomerType, customerDTO.getCustomerType())
                .eq(customerDTO.getStatus() != null, Customer::getStatus, customerDTO.getStatus());
        
        Page<Customer> customerPage = new Page<>(customerDTO.getPage(), customerDTO.getPageSize());
        Page<Customer> page = page(customerPage, lambdaQueryWrapper);


        
        // 使用通用工具类填充区域名称映射（已包含权限过滤后的区域信息）
        DataMappingUtils.buildIdNameMap(
                page.getRecords(),
                Customer::getPowerZoneId,
                powerZoneMapper::selectByIds,
                PowerZone::getId,
                PowerZone::getZoneName,
                powerZoneNameMap
        );
        
        // 使用增强版通用工具类转换并填充区域名称
        // 注意：这里展示了基本用法，如需多外键映射，可以多次调用并传递customerVOList作为existingVOs参数
        List<CustomerVO> customerVOList = DataMappingUtils.convertAndFillNames(
                page.getRecords(),
                CustomerVO.class,
                Customer::getPowerZoneId,
                powerZoneNameMap,
                CustomerVO::setZoneName,
                null  // 首次调用时不需要提供existingVOs
        );

        Page<CustomerVO> customerVOPage = new Page<>();
        BeanUtils.copyProperties(page, customerVOPage);
        customerVOPage.setRecords(customerVOList);
        return Result.success(customerVOPage);
    }

}
